/*
 * Written by Dustin Striplin
 */
package Actions;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;

import Model.Author;
import TableModels.AuthorTemplate;

/**
 * Submits Stores a manuscript
 * @author dustin striplin
 *
 */
public class SubmitManuscript extends AbstractAction{

	JTable table;
	Author author;
	
	public SubmitManuscript(JTable table, Author author) {
		this.table = table;
		this.author = author;
		this.putValue(NAME, "Submit");
		this.putValue(MNEMONIC_KEY, KeyEvent.VK_S);
	}
	
	/**
	 * Saves the manuscript, and stores a representation of it
	 * to the xml file
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		//REMEMBER to cast table model to authortemplate.
		
		//choose file to submit
	    JFileChooser chooser = new JFileChooser();
	    FileNameExtensionFilter filter = new FileNameExtensionFilter(
	        "docx files", "docx");
	    chooser.setFileFilter(filter);
	    int returnVal = chooser.showOpenDialog(null);
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
	    	String title = JOptionPane.showInputDialog("Enter Title");  //get title from user
	    				//tell the model to submit the paper, a confirmation is returned
	    	String confirmation = author.submitPaper(title, "/Papers/" + 
	    									chooser.getSelectedFile().getName());
	    	if(confirmation.equals(Author.SUCCESS)) {

	    		copyFile(chooser.getSelectedFile());
	    		author.getLatestManuscript();
	    		((AuthorTemplate)table.getModel()).addRow(author.getLatestManuscript());  //update the table
	    		table.repaint();
	    	}
	    	JOptionPane.showMessageDialog(null, confirmation);
	    }
		
		

		
	}
	
	
	/**
	 * copies a source file to the papers folder
	 * @param src the source file
	 */
	private void copyFile(File src) {
    	InputStream inStream = null;
		OutputStream outStream = null;

		try{
			String fileName = src.getName();
			
		    File destFile =new File("src/Papers/"+fileName); //don't add a "/" in front
		    												 //of src, errors will
		    												 //ruin your life.
		 
		    	    inStream = new FileInputStream(src);
		    	    outStream = new FileOutputStream(destFile);
		    	    
		    	    byte[] buffer = new byte[1024];
		 
		    	    int length;
		    	    //copy the file content in bytes 
		    	    while ((length = inStream.read(buffer)) > 0){
		 
		    	    	outStream.write(buffer, 0, length);
		 
		    	    }
		 
		    	    inStream.close();
		    	    outStream.close();
		 
		    	}catch(IOException e){
		    		e.printStackTrace();
		    	}
		}
	
}